<?php

namespace app\controller\admin;

use app\common\controller\JwtAuthorizedTrait;
use app\common\exception\CatchException;
use app\common\model\Admin;
use app\common\util\AdminLoginInfo;

class AdminAuthorizedController extends AdminBaseController
{
    use JwtAuthorizedTrait;

    protected function init()
    {
        $admin_id = 0;
        //增加用户端的token支持

        //判断payload的type是否为该端的
        if (isset($this->payload->admin_id)) {
            if (!(isset($this->payload->type) && $this->payload->type == 'admin')) {
                throw new CatchException('无效的token，请重新登录', 608);
            }
        }
        $admin_id = $this->payload->admin_id ?? 0;


        $this->app->bind(Admin::class, function () use ($admin_id) {
            $admin = Admin::find($admin_id);
            if (!$admin) {
                throw new CatchException('无效的用户信息，请重新登录', 608);
            }
            AdminLoginInfo::setAdmin($admin);
            return $admin;
        });
    }

    /**
     * 检查权限
     * @param Admin $admin
     * @param $code
     * @return bool
     * @throws CatchException
     */
    protected function checkPower(Admin $admin, $code): bool
    {
        //判断账号有效性
        if ($admin->valid != 1) {
            throw new CatchException('登录账号已被禁用', 702);
        }

        //超级管理员直接通过
        if ($admin->is_root) {
            return true;
        }

        //获取角色
        $role = $admin->admin_role;
        if (empty($role)) {
            throw new CatchException('登录账号未找到相关角色', 701);
        }

        //获取角色权限
        $codes = $role->codes ?: '';
        $code_array = explode(',', $codes);

        //判断角色权限
        if (!in_array($code, $code_array)) {
            throw new CatchException('登录账号没有相关权限', 700);
        }

        return true;
    }
}
